package com.rt.tmpt.utils.rsa;

import com.rt.tmpt.utils.MD5Util;
import com.rt.tmpt.utils.Utils;

import java.io.File;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.PublicKey;

public class EncodeAction {

	private String pairKeyPath;
	private InputStream keyStream;
	
	public EncodeAction(String pairKeyPath){
		this.pairKeyPath = pairKeyPath;
	}
	public EncodeAction(InputStream keyStream){
		this.keyStream = keyStream;
	}
	
	/**
	 * 先将明文做MD5, 再RSA私钥加密
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public String genEncodeDataByPrivateKey(String data) throws Exception{
		String mingMd5 = MD5Util.toMD5(data);
		byte[] enDataBytes = RSAUtil.encrypt(
				RSAUtil.getKeyPair(this.pairKeyPath).getPrivate(), Utils.hex2byte(mingMd5));
		String enDataHex = Utils.byte2hex(enDataBytes);
		return enDataHex;
	}

	/**
	 * 先将明文做MD5, 再RSA私钥加密
	 * 从文件流中取私钥
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public String genEncodeDataByPrivateKeyFileStream(String data) throws Exception{
		PrivateKey pk = RSAUtil.getKeyPairPrivate(this.keyStream);
		String mingMd5 = MD5Util.toMD5(data);
		byte[] enDataBytes = RSAUtil.encrypt(pk, Utils.hex2byte(mingMd5));
		String enDataHex = Utils.byte2hex(enDataBytes);
		return enDataHex;
	}

	public String decodeDataByPublic(String miByPrivateKey) throws Exception{
		PublicKey pk = RSAUtil.getKeyPairPublic(this.keyStream);
		byte[] mingBytes = RSAUtil.decrypt(pk, Utils.hex2byte(miByPrivateKey));
		
		return Utils.byte2hex(mingBytes);
	}

	
	/**
	 * 如果文件存在return true; 否则return false;
	 * @param path
	 * @return
	 */
	public static boolean isFile(String path){
		File file = new File(path);
		return file.isFile();
	}

	public boolean isFile(){
		File file = new File(this.pairKeyPath);
		return file.isFile();
	}

}
